import Oidc from "oidc-client";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/stores/modules/user";
const authServer = "https://demo.duendesoftware.com/";

export const userManager = new Oidc.UserManager({
  authority: authServer, // 认证服务器
  redirect_uri: window.location.origin + "/oidc/redirectPage", // 表示重定向URI，认证服务器回调的客户端页面。可选项
  post_logout_redirect_uri: window.location.origin + "/oidc/redirectLogout", // 注销成功后的重定向URL
  // demo
  client_id: `login`, // 表示客户端的ID，必选项
  scope: "openid profile email", // 表示申请的权限范围，可选项
  response_type: `id_token`,
  silent_redirect_uri: window.location.origin + "/", // 不能和redirect_uri会导致： signinRedirectCallback异常（ErrorResponse: login_required）
  accessTokenExpiringNotificationTime: 10,
  automaticSilentRenew: true,
  filterProtocolClaims: true,
  loadUserInfo: true,
});

// 重定向登出
export const logOut = async () => {
  console.log("重定向到登出开始");
  await userManager.signoutRedirect();
  userManager.signoutRedirectCallback().then((res) => {
    console.log("重定向到登出成功", res);
  });
};

// 获取登录用户信息
export const getUserMsg = () => {
  let userStore = useUserStore();
  return new Promise((resolve, reject) => {
    userManager
      .getUser()
      .then((user) => {
        let mark = user && user.id_token;
        const {
          profile: { name: userName, id: userId },
        } = user;
        userStore.setUserInfo(user);
        console.log("当前用户信息", user, userId, userName);
        resolve({
          state: mark ? true : false,
          message: mark ? `${"成功获取用户信息"}` : "未获取到用户信息",
          data: mark ? user : {},
        });
      })
      .catch((err) => {
        reject({
          state: false,
          message: `${("获取用户信息失败,失败信息：", err)}`,
          data: null,
        });
      });
  });
};

// 重定向登录
export const redirectLogIn = () => {
  return new Promise((resolve, reject) => {
    userManager
      .signinRedirect()
      .then((res) => {
        resolve({
          state: true,
          message: "重定向登录成功",
          daat: res ? res : null,
        });
      })
      .catch((err) => {
        console.log("-----------", userManager, err, process.env);
        // window.location.href = userManager?.metadataService?.metadataUrl
        ElMessage.error("重定向登录失败");
        reject({
          state: false,
          message: "重定向登录失败",
          daat: err ? err : null,
        });
      });
  });
};

// 移除用户信息
export const removeUser = () => {
  // store.commit("setUserInfo");
  userManager.removeUser();
};

// 登录成功之后的回调
export const handleLoginCallback = () => {
  return new Promise((resolve, reject) => {
    userManager
      .signinRedirectCallback()
      .then((res) => {
        console.log("HOST: 登录成功，即将跳转home", res);
        ElMessage.success("登录成功");
        window.history.replaceState(
          {},
          window.document.title,
          window.location.origin + window.location.pathname
        );
        // 登录成功之后重定向到home页面
        window.location = "/home";
        resolve(true);
      })
      .catch((err) => {
        console.log("HOST: 登录之后回调异常，无法进入home页面", err);
        ElMessage.error("登异异常");
        reject(err);
      });
  });
};

Oidc.Log.logger = console;
Oidc.Log.level = Oidc.Log.INFO;
